// Package account @Author Kings 2022/4/6 15:50:00
package account

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	captcha "github.com/mojocn/base64Captcha"
	"net/http"
	"strings"
	"vben-api/pkg/svc"
	common "vben-common"
)

type CaptchaApi struct {
	store captcha.Store // 验证码存储
}

func NewCaptchaApi(*svc.ServiceContext) *CaptchaApi {
	return &CaptchaApi{
		store: captcha.DefaultMemStore,
	}
}

func NewDriver() *captcha.DriverString {
	driver := new(captcha.DriverString)
	driver.Height = 38
	driver.Width = 120
	driver.NoiseCount = 5
	// driver.ShowLineOptions = captcha.OptionShowSineLine // | captcha.OptionShowSlimeLine | captcha.OptionShowHollowLine
	driver.Length = 4
	driver.Source = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
	driver.Fonts = []string{"wqy-microhei.ttc"}
	return driver
}

// GenerateCaptchaHandle
// @Description: 生成图形验证码
// @receiver l
// @param context
func (l *CaptchaApi) GenerateCaptchaHandle(context *gin.Context) {
	r := common.NewResult()
	id := context.Query("uuid")
	if id == "" {
		context.JSON(http.StatusOK, r.Fail(400, "UUID必填"))
		return
	}
	var driver = NewDriver().ConvertFonts()
	c := captcha.NewCaptcha(driver, l.store)
	_, content, answer := c.Driver.GenerateIdQuestionAnswer()
	context.Header("id", id)
	item, _ := c.Driver.DrawCaptcha(content)
	_ = c.Store.Set(id, strings.ToLower(answer))
	_, _ = item.WriteTo(context.Writer)
}

// CaptchaVerifyHandle
// @Description: 验证码校验
// @receiver l
// @param context
func (l *CaptchaApi) CaptchaVerifyHandle(context *gin.Context) {
	r := common.NewResult()
	id := context.PostForm("uuid") // "captcha:yufei"
	if strings.TrimSpace(id) == "" {
		context.JSON(http.StatusOK, r.Fail(400, "UUID必填"))
		return
	}
	code := context.PostForm("code")
	if code == "" {
		context.JSON(http.StatusOK, r.Fail(400, "验证码必填"))
		return
	}
	if l.store.Verify(id, strings.ToLower(code), true) {
		context.JSON(http.StatusOK, r.Success(nil))
		return
	}
	context.JSON(http.StatusOK, r.Fail(400, "验证码错误"))
}

func (l *CaptchaApi) GetUuid(c *gin.Context) {
	uuidStr := uuid.NewString()
	c.JSON(http.StatusOK, common.NewResult().Success(uuidStr))
}
